package org.bud.db.dynamic.base;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;

import java.util.Optional;
import java.util.function.Function;

/**
 * @author shaun
 * @date 2025/4/1
 * @instruction
 */
public class DynamicVSource extends DruidDataSource implements InitializingBean {
    @Getter
    @Setter
    private String alias;
    @Getter
    @Setter
    private boolean defaultDb;
    @Getter
    private Object dbKey;
    private Function<String,Object> genDbKey;

    public DynamicVSource(Function<String,Object> genDbKey){
        this.genDbKey = genDbKey;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.dbKey = Optional.ofNullable(alias)
                .map(o -> genDbKey.apply(alias))
                .orElseThrow(() -> new IllegalArgumentException("not set the alias as the db key"));
    }
}